<?php

namespace App\Observers;

use App\Models\Coupon;
use Carbon\Carbon;
use App\Notifications\CouponsSend;
use Dcat\Admin\Admin;

class CouponObserver
{
    /**
     * Handle the coupon "created" event.
     *
     * @param  \App\Coupon  $coupon
     * @return void
     */
    public function created(Coupon $coupon)
    {
        //卡券发放通知
        $coupon->user->couponNotify(new CouponsSend($coupon));
    }

    /**
     * Handle the coupon "updated" event.
     *
     * @param  \App\Coupon  $coupon
     * @return void
     */
    public function updated(Coupon $coupon)
    {
        //如果是卡券核销，且是第一次核销 不是误操作之类的
        if($coupon->is_used==1&&!$coupon->used_date)
        {
            $coupon->used_date = Carbon::now()->toDateString();
            //如果没有核销人就表示不是扫码过来的
            if (!$coupon->checker){
                $coupon->checker = Admin::user()->username;
            }
            $coupon->save();
        }
    }

    /**
     * Handle the coupon "deleted" event.
     *
     * @param  \App\Coupon  $coupon
     * @return void
     */
    public function deleted(Coupon $coupon)
    {
        //
    }

    /**
     * Handle the coupon "restored" event.
     *
     * @param  \App\Coupon  $coupon
     * @return void
     */
    public function restored(Coupon $coupon)
    {
        //
    }

    /**
     * Handle the coupon "force deleted" event.
     *
     * @param  \App\Coupon  $coupon
     * @return void
     */
    public function forceDeleted(Coupon $coupon)
    {
        //
    }
}
